<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>物流管理</el-breadcrumb-item>
      <el-breadcrumb-item>物流列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入要查询的订单名："
            v-model="queryInfo.query"
            clearable
            @change="getlogisticsList"
            @clear="getlogisticsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getlogisticsList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- <el-button type="primary" @click="addDialogVisible = true" -->
          <el-button type="primary" @click="showAddDialog">添加物流</el-button>
        </el-col>
      </el-row>

      <!-- 物流信息列表区域 -->
      <el-table :data="logisticslist" blogistics stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column
          label="订单名称"
          prop="logistics_name"
        ></el-table-column>
        <el-table-column
          label="订单数量"
          prop="logistics_num"
        ></el-table-column>
        <el-table-column
          label="订单地址"
          prop="logistics_address"
        ></el-table-column>
        <el-table-column
          label="订单联系人"
          prop="logistics_username"
        ></el-table-column>
        <el-table-column label="手机" prop="logistics_phone"></el-table-column>
        <el-table-column
          label="运输日期"
          prop="logistics_date"
        ></el-table-column>
        <el-table-column
          label="运输车牌号"
          prop="logistics_card"
        ></el-table-column>
        <el-table-column
          label="运输方式"
          prop="logistics_transport"
        ></el-table-column>
        <!-- <el-table-column label="物流地址" prop="logistics_address"></el-table-column> -->
        <!-- <el-table-column label="物流方式" prop="logistics_style"></el-table-column> -->
        <el-table-column
          label="物流状态"
          prop="logistics_status"
          :filters="[
            { text: '运输中', value: '运输中' },
            { text: '送达', value: '送达' },
          ]"
          :filter-method="filterTag"
          filter-placement="bottom-end"
        >
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.logistics_status === '运输中' ? 'primary' : 'success'
              "
              disable-transitions
              >{{ scope.row.logistics_status }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- {{ scope.row.id }}  -->
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.logistics_id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row)"
            ></el-button>
            <!-- 修改物流状态按钮 -->
            <!-- <el-tooltip
              effect="dark"
              content="修改物流运输状态"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setStatus(scope.row)"
              ></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加物流的对话框 -->
    <el-dialog
      title="添加物流"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="140px"
      >
        <el-form-item label="订单名称" prop="logistics_name">
          <!-- <el-input v-model="addForm.logistics_name"></el-input> -->
          <el-select
            v-model="addForm.logistics_name"
            placeholder="请选择"
            @change="getOrderData"
          >
            <el-option
              v-for="item in orderNameList"
              :key="item.id"
              :label="item.order_name"
              :value="item.order_name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单数量" prop="logistics_num">
          <el-input v-model="addForm.logistics_num"></el-input>
        </el-form-item>
        <el-form-item label="订单地址" prop="logistics_address">
          <el-input v-model="addForm.logistics_address"></el-input>
        </el-form-item>
        <el-form-item label="可用车牌号" prop="logistics_card">
          <!-- <el-input v-model="addForm.logistics_card"></el-input> -->
          <el-select
            v-model="addForm.logistics_card"
            placeholder="请选择"
            @change="getCarData"
          >
            <el-option
              v-for="item in carCardList"
              :key="item.id"
              :label="item.car_card"
              :value="item.car_card"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流联系人" prop="logistics_username">
          <el-input v-model="addForm.logistics_username"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话" prop="logistics_phone">
          <el-input v-model="addForm.logistics_phone"></el-input>
        </el-form-item>
        <el-form-item label="运输日期" prop="logistics_date">
          <!-- <el-input v-model="editForm.logistics_date"></el-input> -->
          <el-date-picker
            v-model="addForm.logistics_date"
            type="datetime"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="运输方式" prop="logistics_transport">
          <el-input v-model="addForm.logistics_transport"></el-input>
        </el-form-item>

        <el-form-item label="物流状态" prop="logistics_status">
          <!-- <el-input v-model="editForm.logistics_status"></el-input> -->
          <el-select v-model="addForm.logistics_status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addlogistics">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改物流信息的对话框 -->
    <el-dialog
      title="修改物流信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="90px"
      >
        <el-form-item label="订单名称" prop="logistics_name">
          <el-input v-model="editForm.logistics_name"></el-input>
        </el-form-item>
        <el-form-item label="订单数量" prop="logistics_num">
          <el-input v-model="editForm.logistics_num"></el-input>
        </el-form-item>
        <el-form-item label="订单地址" prop="logistics_address">
          <el-input v-model="editForm.logistics_address"></el-input>
        </el-form-item>
        <el-form-item label="车牌号" prop="logistics_card">
          <el-input v-model="editForm.logistics_card"></el-input>
        </el-form-item>
        <el-form-item label="物流联系人" prop="logistics_username">
          <el-input v-model="editForm.logistics_username"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话" prop="logistics_phone">
          <el-input v-model="editForm.logistics_phone"></el-input>
        </el-form-item>
        <el-form-item label="运输日期" prop="logistics_date">
          <!-- <el-input v-model="editForm.logistics_date"></el-input> -->
          <el-date-picker
            v-model="editForm.logistics_date"
            type="datetime"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="运输方式" prop="logistics_transport">
          <el-input v-model="editForm.logistics_transport"></el-input>
        </el-form-item>

        <el-form-item label="物流状态" prop="logistics_status">
          <!-- <el-input v-model="editForm.logistics_status"></el-input> -->
          <el-select v-model="editForm.logistics_status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editlogisticsInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'logistics',
  data() {
    // 自定义验证手机号的规则
    var checkphone = (rules, value, cb) => {
      // 验证手机号的正则表达式
      const regphone = /^1[3|4|5|7|8][0-9]{9}$/

      if (regphone.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      tableData: [],
      token: '',
      // -----------------
      // 获取物流信息列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      logisticslist: [],
      total: 0,
      // 控制添加物流对话框的显示与隐藏
      addDialogVisible: false,
      // 添加物流的表单数据
      addForm: {
        logistics_name: '',
        logistics_num: '',
        logistics_address: '',
        logistics_card: '',
        logistics_username: '',
        logistics_phone: '',
        logistics_date: '',
        logistics_transport: '',
        logistics_status: '',
      },
      // 添加表单的验证规则对象
      addFormRules: {
        logistics_name: [
          { required: true, message: '请输入订单名称', trigger: 'blur' },
        ],
        logistics_num: [
          { required: true, message: '请输入订单数量', trigger: 'blur' },
        ],
        logistics_address: [
          { required: true, message: '请输入订单地址', trigger: 'blur' },
        ],
        logistics_card: [
          { required: true, message: '请输入物流号', trigger: 'blur' },
        ],
        // logistics_style: [
        //   { required: true, message: '请输入物流类型', trigger: 'blur' },
        // ],
        logistics_date: [
          { required: true, message: '请输入日期', trigger: 'blur' },
        ],
        logistics_transport: [
          { required: true, message: '请输入物流方式', trigger: 'blur' },
        ],
        logistics_username: [
          { required: true, message: '请输入物流用户名', trigger: 'blur' },
          // { validator: checkEmail, trigger: 'blur' },
        ],
        logistics_phone: [
          { required: true, message: '请输入手机', trigger: 'change' },
          { validator: checkphone, trigger: 'change' },
        ],
        // logistics_address: [
        //   { required: true, message: '请输入物流地址', trigger: 'blur' },
        // ],
        // logistics_style: [
        //   { required: true, message: '请输入物流类型', trigger: 'blur' },
        // ],
        logistics_status: [
          {
            required: true,
            // type: Number,
            message: '请选择物流状态，0代表空闲，1代表空闲',
            trigger: 'change',
          },
        ],
      },
      // 物流状态选择
      options: [
        {
          value: '0',
          label: '运输中',
        },
        {
          value: '1',
          label: '送达',
        },
      ],
      // 物流类型选择
      logisticstyle: [
        {
          value: '普通',
          label: '普通',
        },
        {
          value: '重型货车',
          label: '重型货车',
        },
        {
          value: '中型货车',
          label: '中型货车',
        },
        {
          value: '轻型货车',
          label: '轻型货车',
        },
        {
          value: '微型货车',
          label: '微型货车',
        },
      ],
      // 控制修改物流信息对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的物流信息信息对象
      editForm: {},
      // 修改表单的 验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入物流信息邮箱', trigger: 'blur' },
          // { validator: checkEmail, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入物流信息手机号', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur' },
        ],
      },
      // 控制分配角色对话框的显示与隐藏
      setStatusDialogVisible: false,
      // 需要被分配角色（那一行）的物流信息信息
      userInfo: {},
      // 所有角色的数据列表
      statusList: [],
      // 已选中的角色id值
      selectedRoled: '',
      // 添加对话框中订单名称 数据
      orderNameList: [],
      // 添加对话框中可用车牌号 数据
      carCardList: [],
    }
  },
  created() {
    if (this.$route.query.order_name) {
      this.queryInfo.query = this.$route.query.order_name
    }
    this.getlogisticsList()
  },
  computed: {
    getuserInfo() {
      return this.$store.state.userInfo
    },
  },
  methods: {
    // 获取所有物流信息信息
    getlogisticsList() {
      this.$http
        .get('/myApi/logistics/logisticsinfoAll', {
          params: this.queryInfo,
        })
        .then((res) => {
          console.log(res.data, '00000000000')
          if (res.data.code == 200) {
            res.data.data.filter((item) => {
              item.logistics_date = item.logistics_date
                .split('')
                .splice(0, 10)
                .join('')
              item.logistics_status =
                item.logistics_status == 0 ? '运输中' : '送达'
            })
            this.logisticslist = res.data.data
            this.total = res.data.total
          }
        })
    },
    // 展示添加对话框
    showAddDialog() {
      this.addDialogVisible = true
      // 获取订单名称
      this.getOrderName()
      // 获取可用车牌号数据
      this.getCarCard()
    },
    // 获取订单名称
    getOrderName() {
      this.$http.get('/myApi/order/ordername').then((res) => {
        if (res.data.code == 200) {
          console.log(res.data, '订单名称数据')
          this.orderNameList = res.data.data
        }
      })
    },
    // 获取可用车牌号
    getCarCard() {
      this.$http.get('/myApi/car/carcard').then((res) => {
        if (res.data.code == 200) {
          console.log(res.data, '可用车牌号数据')
          this.carCardList = res.data.data
        }
      })
    },
    // 订单名称 下拉框变化时触发， 根据下拉框选中的订单名，获取对应的订单信息
    getOrderData() {
      var name = this.addForm.logistics_name
      this.$http.get(`/myApi/order/ordername/${name}`).then((res) => {
        if (res.data.code == 200) {
          console.log(res.data, '订单数据')
          // this.orderNameList = res.data.data
          var orderData = res.data.data
          this.addForm.logistics_num = orderData.order_num
          this.addForm.logistics_username = orderData.order_username
          this.addForm.logistics_phone = orderData.order_phone
          this.addForm.logistics_address = orderData.order_address
          // this.addForm.logistics_style = orderData.order_style
        }
      })
    },
    // 车牌号 下拉框变化时触发， 根据下拉框选中的订单名，获取对应的订单信息
    getCarData() {
      var canUsecard = this.addForm.logistics_card
      this.$http.get(`/myApi/car/carcard/${canUsecard}`).then((res) => {
        if (res.data.code == 200) {
          console.log(res.data, '订单数据')
          // this.orderNameList = res.data.data
          var carData = res.data.data
          this.addForm.logistics_transport = carData.car_transport
        }
      })
    },
    // 修改对话框
    async showEditDialog(id) {
      // 根据传进来的id 发起 axios请求，得到对物流信息的信息
      const { data: res } = await this.$http.get(
        '/myApi/logistics/logisticsinfo/' + id
      )
      console.log(res, '???????')
      if (res.code !== 200) {
        return this.$message.error('查询物流信息信息失败')
      }
      this.$message.success('查询物流信息信息成功')
      // 请求成功后将物流信息的信息保存到 data中
      this.editForm = res.data
      console.log(this.editForm.logistics_status, 'mmmmmmmmmmmmmmmmmmmmmm')
      this.editForm.logistics_status =
        this.editForm.logistics_status == 0 ? '运输中' : '送达'

      this.editDialogVisible = true
      // console.log(id)
    },
    // 监听修改物流信息对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改物流信息信息并提交
    editlogisticsInfo() {
      // validate()是提交前 对整个表单进行校验的方法
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return
        console.log(this.editForm.logistics_status, 'zzzzzzzzzzzzzzzzzz')

        // 可以发起修改物流信息的网络请求
        const { data: res } = await this.$http.post(
          '/myApi/logistics/logisticsinfo/' + this.editForm.logistics_id,
          this.editForm
        )
        console.log(res)
        if (res.code !== 200) {
          return this.$message.error('更新物流信息信息失败')
        }
        // 隐藏修改物流信息的对话框
        this.editDialogVisible = false
        // 提示修改成功
        this.$message.success('更新物流信息信息成功')

        // 修改车辆管理信息===================
        this.editCarData(this.editForm)
        // 修改订单管理信息====================
        this.editOrderData(this.editForm)

        // 重新渲染数据
        this.getlogisticsList()
      })
    },
    // 根据id 删除对应的物流信息信息
    async removeUserById(rowInfo) {
      // 弹框询问物流信息是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该物流信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) // cancel
      // 如果物流信息点击确认 删除，则返回值为 字符串 confirm
      // 如果物流信息点击取消 删除，则返回值为 字符串 cancel
      // console.log(confirmResult) // Promise对象
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除!')
      }
      // console.log('确认了删除')
      const { data: res } = await this.$http.delete(
        '/myApi/logistics/logisticsinfo/' + rowInfo.logistics_id
      )

      if (res.code !== 200) {
        return this.$message.error('删除物流信息信息失败!')
      }
      this.$message.success('删除物流信息信息成功')
      // 修改订单管理信息====================
      var order_name = rowInfo.logistics_name
      this.$http
        .post(`/myApi/order/orderstatus/${order_name}`, {
          // order_status: name.logistics_status == 0 ? 1 : 0,
          order_status: 0, //删除代表 未发货 ，0代表未发货
        })
        .then((res) => {
          console.log(res.data)
          if (res.data.code !== 200) {
            this.$message.warning('修改订单状态失败')
          } else {
            this.$message.success('修改订单状态成功')
          }
        })
      // 修改车辆管理信息===================
      var car_card = rowInfo.logistics_card
      this.$http
        .post(`/myApi/car/carcard/${car_card}`, {
          car_status: 0, //直接让车辆状态改为 空闲
          car_date: rowInfo.logistics_date,
          car_transport: rowInfo.logistics_transport,
        })
        .then((res) => {
          console.log(res.data)
          if (res.data.code !== 200) {
            this.$message.warning('修改车辆信息失败')
          } else {
            this.$message.success('修改车辆信息成功')
          }
        })
      // 重新渲染列表
      this.getlogisticsList()
    },

    // 监听添加物流对话框的关闭事件
    addDialogClosed() {
      // 拿到对话框的引用，调用自身的resetFields方法，重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 添加物流信息
    addlogistics() {
      this.$refs['addFormRef'].validate((valid) => {
        // 校验失败
        if (!valid) return console.log('添加物流信息失败!!')
        console.log(this.addForm.logistics_date)
        // this.addForm.logistics_date = this.addForm.logistics_date
        //   .split('')
        //   .splice(0, 10)
        //   .join('')
        // 添加物流信息
        this.$http
          .post('/myApi/logistics/addlogisticsinfo', this.addForm)
          .then((res) => {
            console.log(res.data)
            if (res.data.code !== 200) {
              this.$message.warning('添加失败，物流信息名或密码错误')
            } else {
              this.$message.success('添加物流成功')
              // 隐藏添加物流的对话框
              this.addDialogVisible = false
              this.getlogisticsList()
            }
          })

        // 修改订单管理信息====================
        this.editOrderData(this.addForm)
        // 修改车辆管理信息===================
        this.editCarData(this.addForm)
      })
    },
    editOrderData(name) {
      var order_name = name.logistics_name
      this.$http
        .post(`/myApi/order/orderstatus/${order_name}`, {
          // order_status: name.logistics_status == 0 ? 1 : 0,
          order_status: 1, //运输中和送达 都已经发货 ，1代表发货
        })
        .then((res) => {
          console.log(res.data)
          if (res.data.code !== 200) {
            this.$message.warning('修改订单状态失败')
          } else {
            // this.$message.success('修改订单状态成功')
          }
        })
    },
    editCarData(name) {
      var car_card = name.logistics_card
      this.$http
        .post(`/myApi/car/carcard/${car_card}`, {
          car_status: name.logistics_status == 0 ? 1 : 0,
          car_date: name.logistics_date,
          car_transport: name.logistics_transport,
        })
        .then((res) => {
          console.log(res.data)
          if (res.data.code !== 200) {
            this.$message.warning('修改车辆信息失败')
          } else {
            // this.$message.success('修改车辆信息成功')
          }
        })
    },
    // 分页=========
    // 监听pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      console.log(this.queryInfo.pagesize, 'pagesize')
      this.getlogisticsList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      console.log(this.queryInfo.pagenum, 'pagenum')
      this.getlogisticsList()
    },

    filterTag(value, row) {
      return row.logistics_status === value
    },
  },
}
</script>

<style lang="less" scoped>
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
